package com.zzyl.nursing.service.impl;

import java.time.*;
import java.util.*;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.domain.Reservation;
import com.zzyl.nursing.dto.ReservationDto;
import com.zzyl.nursing.dto.ReservationListDto;
import com.zzyl.nursing.mapper.ReservationMapper;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.zzyl.nursing.service.IReservationService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 预约信息Service业务层处理
 *
 * @author ruoyi
 * @date 2025-03-02
 */
@Service
public class ReservationServiceImpl extends ServiceImpl<ReservationMapper, Reservation> implements IReservationService
{
    @Autowired
    private ReservationMapper reservationMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IFamilyMemberService memberService;


        /**
         * 查询预约信息
         *
         * @param id 预约信息主键
         * @return 预约信息
         */
        @Override
        public Reservation selectReservationById(Long id) {
            return getById(id);
        }

        /**
         * 查询预约信息列表
         *
         * @param reservation 预约信息
         * @return 预约信息
         */
        @Override
        public List<Reservation> selectReservationList(Reservation reservation) {
            return reservationMapper.selectReservationList(reservation);
        }

        @Override
        public int insertReservation(ReservationDto reservationDto) {
            Reservation reservation = new Reservation();
            BeanUtils.copyProperties(reservationDto, reservation);
            reservation.setStatus(0);
            save(reservation);
            return 1;
        }





        /**
         * 查询当天取消预约数量
         *
         * @return
         */
        @Override
        public Long cancelledCount() {
            // 获取当前时间的时间戳（以毫秒为单位）
            long time = System.currentTimeMillis();
            // 将时间戳转换为 LocalDateTime 对象
            LocalDateTime ldt = LocalDateTimeUtil.of(time);
            // 将 ldt 转换为 LocalDat
            LocalDateTime startTime = ldt.toLocalDate().atStartOfDay();
            //  在 startTime 的基础上加上一天
            LocalDateTime endTime = startTime.plusDays(1);

            LambdaQueryWrapper<Reservation> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.between(Reservation::getTime, startTime, endTime);
            queryWrapper.eq(Reservation::getStatus, 2);
            queryWrapper.eq(Reservation::getType, 0);
            return count(queryWrapper);
        }

   /* @Override
    public long reservationListRm() {
      //1.获取当前时间的毫秒值
       long time = System.currentTimeMillis();
       //将毫秒值转换为LocalDateTime
      LocalDateTime ldt = LocalDateTimeUtil.of(time);
       //获取当天的开始时间
        LocalDateTime startTime = ldt.toLocalDate().atStartOfDay();
        LocalDate startTime1=startTime.toLocalDate();
        //获取当天的结束时间
       LocalDateTime endTime = startTime.plusDays(1);

        endTime=endTime.plusDays(1);
        LocalDate endTime1=endTime.toLocalDate();
       LambdaQueryWrapper<Reservation> queryWrapper = Wrappers.lambdaQuery();
       //查询预约状态status为2的数据,2为取消;
        queryWrapper.eq(Reservation::getStatus, 2);
       //查询预约时间大于开始时间
       queryWrapper.ge(Reservation::getTime, startTime1);
        //查询预约时间小于结束时间
        queryWrapper.lt(Reservation::getTime, endTime1);
        //查询参观预约
        queryWrapper.eq(Reservation::getType,"0");


        return count(queryWrapper);
    }*/

        @Override
        public long reservationListRm() {
            // 1. 获取当前时间的毫秒值
            long time = System.currentTimeMillis();
            // 将毫秒值转换为 LocalDateTime
            LocalDateTime ldt = LocalDateTimeUtil.of(time);
            LocalDate dayNow=ldt.toLocalDate();
            // 获取当天的开始时间
            LocalDateTime startTime = ldt.toLocalDate().atStartOfDay();
            // 获取当天的结束时间
            LocalDateTime endTime = startTime.plusDays(1);

     /*   DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
        String startTimeStr = startTime.format(formatter);
        String endTimeStr = endTime.format(formatter);
*/
            // 构建查询条件
            LambdaQueryWrapper<Reservation> queryWrapper = Wrappers.lambdaQuery();
            // 查询预约状态 status 为 2 的数据，2 表示取消
            queryWrapper.eq(Reservation::getStatus, 2);
            // 查询预约时间大于等于开始时间
            queryWrapper.ge(Reservation::getTime, startTime);
            // 查询预约时间小于结束时间
            queryWrapper.lt(Reservation::getTime, endTime);
            // 查询参观预约，类型为 0
            queryWrapper.eq(Reservation::getType, 0);
            //Long l = UserThreadLocal.get();
            //FamilyMember byId = memberService.getById(l);

            // 查询满足条件的预约数量
            return count(queryWrapper);
        }

        @Override
        public List<ReservationListDto> reservationList(Long time) {
            // 将时间戳转换为 LocalDateTime
            Instant instant = Instant.ofEpochMilli(time);
            LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
            LocalDate localDate = ldt.toLocalDate();
            return reservationMapper.selectTime(localDate);
        }

        @Override
        public Page reservationPage(Integer pageSize, Integer pageNum, Integer status) {
            Page<Reservation> page = new Page<>(pageNum, pageSize);
            Long userId = UserThreadLocal.get();
            LambdaQueryWrapper<FamilyMember> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(FamilyMember::getOpenId, userId);
            FamilyMember byId = memberService.getById(userId);
            LambdaQueryWrapper<Reservation> queryWrapper = Wrappers.lambdaQuery();
            if (status != null) {
                queryWrapper.eq(Reservation::getStatus, status);
            }
            queryWrapper.eq(Reservation::getMobile, byId.getPhone());
            page = page(page, queryWrapper);
            return page;
        }

        @Override
        public void autoCancel() {
            // 1.查询状态为0的预约  && 预约开始时间小于等于当前时间
            List<Reservation> list = list(Wrappers.<Reservation>lambdaQuery()
                    .eq(Reservation::getStatus, 0)
                    .le(Reservation::getTime, LocalDateTime.now()));
            // 2.修改状态为1
            list.forEach(item -> {
                item.setStatus(3);
            });

            // 3.批量更新
            updateBatchById(list);
        }

        /**
         * 更新合同状态
         */
        @Override
        public void updateReservationStatus() {
            List<Reservation> list = list(Wrappers.<Reservation>lambdaQuery()
                    .eq(Reservation::getStatus, 0)
                    .le(Reservation::getTime, DateUtils.getNowDate()));

            list.forEach(item -> {
                item.setStatus(3);
            });
            updateBatchById(list);
        }

        /**
         * 取消预约
         *
         * @param id
         */
        @Override
        public int cancel(Long id) {
            Reservation reservation = getById(id);
            if (reservation == null) {
                throw new BaseException("预约不存在");
            }
            reservation.setStatus(2);
            reservation.setUpdateBy(UserThreadLocal.get().toString());
            return updateById(reservation) ? 1 : 0;
        }
    }

